//
//  NearplaceViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/16.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "NearplaceViewController.h"

#import "CityModel.h"
#import "PlaceCell.h"
@interface NearplaceViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,BMKGeoCodeSearchDelegate,BMKPoiSearchDelegate,BMKLocationServiceDelegate,BMKSuggestionSearchDelegate>{
    
    BMKSuggestionResult *sugges;//地址搜索
    BMKLocationService *location;//定位
    BMKGeoCodeSearch *geocodeSearch;//饭编码
    BMKPoiSearch *poisearch;//检索
    NSMutableArray *array;
    PlaceCell *placecell;
    CGFloat angle;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,copy)NSString *searchStr;//搜索内容
@property (nonatomic,copy)NSString *place;

@property (nonatomic,copy)NSString *searchState;

@end

@implementation NearplaceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self showNav:@"选择地址"];
    array = [NSMutableArray array];
    [self location];
    [self loadUI];
    
}

- (void)location{
    poisearch = [[BMKPoiSearch alloc] init];
    poisearch.delegate = self;
    
    location = [[BMKLocationService alloc] init];
    location.delegate = self;
    [location startUserLocationService];
    
    //反编码
    geocodeSearch = [[BMKGeoCodeSearch alloc] init];
    geocodeSearch.delegate = self;
    
    BMKNearbySearchOption *option = [[BMKNearbySearchOption alloc] init];
    option.pageIndex = 1;
    option.pageCapacity = 10;
    option.location = CLLocationCoordinate2DMake(_lat, _lng);
    option.keyword = @"小区";
    BOOL flag = [poisearch poiSearchNearBy:option];
    if (flag) {
        NSLog(@"周边检索发送成功");
    }else{
        NSLog(@"周边检索发送失败");
    }
    
}
#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    
    BOOL flag = [geocodeSearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
        //停止定位
        [location stopUserLocationService];
        
    }else{
        NSLog(@"反geo检索发送失败");
    }
    [location stopUserLocationService];
}

#pragma -mark BMKGeoCodeSearchDelegate
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    
    NSLog(@"%@---%@---%@--%@",result.addressDetail,result.address,result.businessCircle,result.addressDetail.district);
    _place = result.address;
    [_tableView reloadData];
}

#pragma -mark BMKPoiSearchDelegate
-(void)onGetPoiResult:(BMKPoiSearch *)searcher result:(BMKPoiResult *)poiResult errorCode:(BMKSearchErrorCode)errorCode{
    if (errorCode == BMK_SEARCH_NO_ERROR) {
        [array removeAllObjects];
        for(BMKPoiInfo *poiInfo in poiResult.poiInfoList)
        {
            NSString *name = poiInfo.name;
            NSString *address = poiInfo.address;
            CityModel *model = [[CityModel alloc] init];
            model.name = name;
            model.address = address;
            [array addObject:model];
            [_tableView reloadData];
        }
    }
}

- (void)loadUI{
    UISearchBar *searBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, 30)];
    searBar.placeholder = @"输入您想要搜索的地址";
//    [searBar setShowsCancelButton:YES animated:YES];
    searBar.delegate = self;
    [self.view addSubview:searBar];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64+30, ScreenWidth, ScreenHeight-64-30) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
}

-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    [searchBar setShowsCancelButton:YES animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    
    return YES;
}
//点击搜索按钮
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    _searchStr = searchBar.text;
    NSLog(@"%@",searchBar.text);
    [searchBar resignFirstResponder];
    
    BMKSuggestionSearch *sear = [[BMKSuggestionSearch alloc] init];
    sear.delegate = self;
    
    BMKSuggestionSearchOption *option = [[BMKSuggestionSearchOption alloc] init];
    option.keyword = _searchStr;
    [sear suggestionSearch:option];
    
}

-(void)onGetSuggestionResult:(BMKSuggestionSearch *)searcher result:(BMKSuggestionResult *)result errorCode:(BMKSearchErrorCode)error{
    if (error == BMK_SEARCH_NO_ERROR) {
        
        [array removeAllObjects];
        
        NSArray *arr1 = result.keyList;
        _searchState = @"aaa";
        array = [arr1 mutableCopy];
        NSLog(@"array:%@",array);
//        NSArray *arr2 = result.cityList;
//        NSArray *arr3 = result.districtList;
        [_tableView reloadData];
    }else {
        NSLog(@"抱歉，未找到结果");
    }
}

//点击取消按钮
-(void)searchBarCancelButtonClicked:(UISearchBar*)searchBar
{
    NSLog(@"searchBarCancelButtonClicked");
    [searchBar resignFirstResponder];
    [searchBar setShowsCancelButton:NO animated:YES];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
#pragma -mark UITableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *cellId = @"Cell0";
        placecell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!placecell) {
            placecell = [[[NSBundle mainBundle] loadNibNamed:@"PlaceCell" owner:nil options:nil] lastObject];
        }
        placecell.selectionStyle = UITableViewCellSelectionStyleNone;
        placecell.labText.text = _place;
        [placecell.btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];
        
        return placecell;
    }else{
        static NSString *cellId = @"Cell1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if ([_searchState isEqualToString:@"aaa"]) {
            cell.textLabel.text = array[indexPath.row];
        }else{
            CityModel *model = array[indexPath.row];
            cell.textLabel.text = model.name;
            cell.detailTextLabel.text = model.address;
        }
        
        return cell;
    }
    
}
//重新定位
- (void)click{
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI*2.0];
    rotationAnimation.duration = 1;
    rotationAnimation.repeatCount = HUGE_VALF;
    
    [placecell.images.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(sleep:) userInfo:nil repeats:NO];
    
}

- (void)sleep:(NSTimer *)time{
    [time invalidate];
    [placecell.images.layer removeAllAnimations];
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str;
    if (indexPath.section == 0) {
        str = _place;
        [self.delegate sendPlace:str];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        str = array[indexPath.row];
        if ([_searchState isEqualToString:@"aaa"]) {
            [self.delegate sendPlace:str];
        }else{
            CityModel *model = array[indexPath.row];
            [self.delegate sendPlace:model.address];
        }
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 50.0;
    }
    return 44.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(16, 10, 100, 20)];
    
    if (section==0) {
       lab.text = @"当前位置";
    }else{
       lab.text = @"附近位置";
    }
    [view addSubview:lab];
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40.0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
